// sm2gj.c
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <gmssl/sm2.h>

int main() {
    SM2_KEY key;
    unsigned char plaintext[] = "20231318fsl";
    size_t plaintext_len = strlen((char*)plaintext);

    // 使用 GmSSL 定义的最大密文长度（366）
    unsigned char ciphertext[SM2_MAX_CIPHERTEXT_SIZE];
    size_t ciphertext_len = sizeof(ciphertext);

    // 解密缓冲区：最大明文长度为 SM2_MAX_PLAINTEXT_SIZE (255)
    unsigned char decrypted[SM2_MAX_PLAINTEXT_SIZE + 1];
    size_t decrypted_len = sizeof(decrypted);

    // 1. 生成 SM2 密钥对
    if (!sm2_key_generate(&key)) {
        fprintf(stderr, "Failed to generate SM2 key pair\n");
        return 1;
    }

    // 2. 加密
    if (!sm2_encrypt(&key, plaintext, plaintext_len, ciphertext, &ciphertext_len)) {
        fprintf(stderr, "SM2 encryption failed\n");
        return 1;
    }

    printf("Plaintext: %s\n", plaintext);
    printf("Ciphertext length: %zu\n", ciphertext_len);

    // 3. 解密
    if (!sm2_decrypt(&key, ciphertext, ciphertext_len, decrypted, &decrypted_len)) {
        fprintf(stderr, "SM2 decryption failed\n");
        return 1;
    }

    decrypted[decrypted_len] = '\0';
    printf("Decrypted: %s\n", decrypted);

    // 4. 验证
    if (plaintext_len == decrypted_len && memcmp(plaintext, decrypted, plaintext_len) == 0) {
        printf("SM2 encrypt/decrypt success!\n");
    } else {
        fprintf(stderr, "Decryption mismatch!\n");
        return 1;
    }

    return 0;
}
